<template>
  <div class="search">
    <van-nav-bar title="搜索" />
    
    <van-search
      v-model="keyword"
      show-action
      placeholder="搜索课程"
      @search="onSearch"
      @cancel="onCancel"
    />

    <div class="search-history" v-if="!keyword && searchHistory.length">
      <van-cell-group title="搜索历史">
        <van-cell 
          v-for="item in searchHistory" 
          :key="item"
          :title="item"
          @click="keyword = item"
        >
          <template #right-icon>
            <van-icon name="cross" @click.stop="removeHistory(item)" />
          </template>
        </van-cell>
      </van-cell-group>
    </div>

    <div class="search-result" v-if="courses.length">
      <van-card
        v-for="course in courses"
        :key="course.id"
        :price="course.price"
        :title="course.title"
        :desc="course.description"
        :thumb="'https://via.placeholder.com/100'"
        @click="goToCourseDetail(course.id)"
      />
    </div>

    <van-empty 
      v-if="keyword && !courses.length" 
      description="暂无搜索结果" 
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { showToast } from 'vant';
import { courseApi } from '@/api';
import type { Course } from '@/api/types';

const router = useRouter();
const keyword = ref('');
const courses = ref<Course[]>([]);
const searchHistory = ref<string[]>([]);

const onSearch = async () => {
  if (!keyword.value) return;
  try {
    const { data } = await courseApi.searchCourses(keyword.value);
    courses.value = data.data;
    if (!searchHistory.value.includes(keyword.value)) {
      searchHistory.value.unshift(keyword.value);
      if (searchHistory.value.length > 10) {
        searchHistory.value.pop();
      }
    }
  } catch (error) {
    showToast('搜索失败');
  }
};

const onCancel = () => {
  keyword.value = '';
  courses.value = [];
};

const removeHistory = (item: string) => {
  searchHistory.value = searchHistory.value.filter(h => h !== item);
};

const goToCourseDetail = (id: number) => {
  router.push(`/course/${id}`);
};
</script>

<style scoped>
.search {
  min-height: 100vh;
  background: #f7f8f8;
}

.search-result {
  padding: 10px;
}

.van-card {
  margin-bottom: 10px;
  background: #fff;
}
</style>
